package controllers

import (
	//	"fmt"
	"token/utils/binding"

	//	"token/utils/validator"

	"token/models"

	"token/utils/encrypt"

	"github.com/gin-gonic/gin"
)

type applyIDParams struct {
	//	User     string `form:"user" json:"user" binding:"required"`
	//	Password string `form:"password" json:"password" binding:"required"`
	Mac    string `form:"mac" json:"mac_addr" binding:"required"`
	ID     string `form:"id" json:"id" binding:"required"`
	Domain string `form:"domain" json:"domain" binding:"required"`
}

func ApplyID(c *gin.Context) {
	//	panic(233)
	var params applyIDParams

	b := binding.Binding{
		ContentType: c.ContentType(),
	}

	if err := c.ShouldBindWith(&params, b); err != nil {
		c.JSON(400, gin.H{
			"result": 1020000,
			"msg":    err.Error(),
			"data":   nil,
		})
		return
	}
	if !encrypt.MacCheck(params.Mac) {
		c.JSON(400, gin.H{
			"result": 1020000,
			"msg":    "invalid mac",
			"data":   nil,
		})
		return
	}
	gin.DefaultWriter.Write([]byte("mac:" + params.Mac + ";id:" + params.ID + ";domain:" + params.Domain))

	user := &models.User{}

	res := user.GetUser(params.Mac, params.Domain)
	if !res {
		c.JSON(200, gin.H{
			"result": 1023330,
			"msg":    "no more",
			"data":   nil,
		})
	} else {
		user.User = encrypt.Encrypt(user.User, 1, params.ID)
		c.JSON(200, gin.H{
			"result": 0,
			"msg":    nil,
			"data":   user,
		})
	}

}

func UpdateUser(c *gin.Context) {
	var params applyIDParams

	b := binding.Binding{
		ContentType: c.ContentType(),
	}

	if err := c.ShouldBindWith(&params, b); err != nil {
		c.JSON(400, gin.H{
			"result": 1020000,
			"msg":    err.Error(),
			"data":   nil,
		})
		return
	}

	gin.DefaultWriter.Write([]byte("mac:" + params.Mac + ";id:" + params.ID + ";domain:" + params.Domain))

	user := &models.User{}

	user.UpdateUser(params.Mac)

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"result": 1023333,
			"msg":    "expire",
			"data":   nil,
		})
	} else {
		user.User = encrypt.Encrypt(user.User, 1, params.ID)
		c.JSON(200, gin.H{
			"result": 0,
			"msg":    nil,
			"data":   user,
		})
	}
}

func SignOut(c *gin.Context) {
	var params applyIDParams

	b := binding.Binding{
		ContentType: c.ContentType(),
	}

	if err := c.ShouldBindWith(&params, b); err != nil {
		c.JSON(400, gin.H{
			"result": 1020000,
			"msg":    err.Error(),
			"data":   nil,
		})
		return
	}

	user := &models.User{}
	user.SignOut(params.Mac)
	c.JSON(200, gin.H{
		"result": 0,
		"msg":    nil,
		"data":   "success",
	})
}
